package zy.blue7.gui;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

/**
 * @Author: blue7
 * @Date: 2022/2/24 19:43
 * @Version 1.0
 * @Description
 */
public class NettyServer {

    public static void start(){

        //todo 1。启动器，负责组装 netty 组件 ，启动服务器
        new ServerBootstrap()
                //todo 2. BossGroup WOrkEventLoop(selector,thread)
                .group(new NioEventLoopGroup())
                //3 选择 服务器的 ServerSocketChannel 实现
                .channel(NioServerSocketChannel.class)
                //4。 boss负责处理链接，worker（child） 负责处理读写，决定力worker能执行哪些读写操作
                .childHandler(
                        // channel  代表和客户端进行数据读写通道    Initializer 初始化，   负责添加其他的handler
                        new ChannelInitializer<NioSocketChannel>() {
                            @Override
                            protected void initChannel(NioSocketChannel ch) throws Exception {

                                // 6. 添加具体的handler
                                ch.pipeline().addLast(new StringDecoder());//todo 将bytebuf转换成string
                                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { // TODO: 2021/9/12 自定义handler
                                    @Override  // TODO: 2021/9/12 读事件
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

                                        System.out.println(msg);
                                    }
                                });
                            }
                        })
                .bind(8080);
    }
}
